package site.yunnong.atvris.security.config;

import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.configurers.ExpressionUrlAuthorizationConfigurer;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import site.yunnong.atvris.security.component.JwtAuthenticationTokenFilter;
import site.yunnong.atvris.security.component.RestAuthenticationEntryPoint;
import site.yunnong.atvris.security.component.RestfulAccessDeniedHandler;
import site.yunnong.atvris.security.util.JwtTokenUtil;

/**
 * @author JinghaoZhang
 * @description
 * @create 2021-03-25 16:47
 */
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    // 用于配置UserDetailsService及PasswordEncoder
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception{
        auth.userDetailsService(userDetailsService())
                .passwordEncoder((encoder()));
    }

    //用于配置需要拦截的url路径、jwt过滤器及出异常后的处理器
    //对不同请求路径执行不同的安全规则
    @Override
    protected void configure(HttpSecurity http) throws Exception{
        ExpressionUrlAuthorizationConfigurer<HttpSecurity>.ExpressionInterceptUrlRegistry registry = http
                .authorizeRequests();

        //配置一个ignoreUrlsConfig允许对一些静态资源的无授权访问
        for (String url : ignoreUrlsConfig().getUrls()) {
            registry.antMatchers(url).permitAll();
        }

        registry.antMatchers(HttpMethod.OPTIONS) //跨域请求会先进行一次options请求
                .permitAll();

//        registry.and() // 测试用
//                .authorizeRequests()
//                .anyRequest()
//                .permitAll();

//         所有请求，都需要认证
        registry.and()
                .authorizeRequests()
                .anyRequest()
                .authenticated()
                .and() //使用JWT不需要csrf
                .csrf()
                .disable()
                .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                //自定义权限拒绝处理类
                .and()
                .exceptionHandling()
                .accessDeniedHandler(restfulAccessDeniedHandler())
                .authenticationEntryPoint(restAuthenticationEntryPoint())
                .and()
                .addFilterBefore(jwtAuthenticationTokenFilter(), UsernamePasswordAuthenticationFilter.class);
    }
//
    @Bean
    public PasswordEncoder encoder(){
        return new BCryptPasswordEncoder();
    }

    @Bean
    public IgnoreUrlsConfig ignoreUrlsConfig(){
        return new IgnoreUrlsConfig();
    }

    /**
     * Jwt授权过滤器
     * @return
     */
    @Bean
    public JwtAuthenticationTokenFilter jwtAuthenticationTokenFilter() {
        return new JwtAuthenticationTokenFilter();
    }

    /**
     * Jwt无权限时自定义返回
     * @return
     */
    @Bean
    public RestfulAccessDeniedHandler restfulAccessDeniedHandler() {
        return new RestfulAccessDeniedHandler();
    }

    /**
     * 未登录或登录过期时自定义返回内容
     * @return
     */
    @Bean
    public RestAuthenticationEntryPoint restAuthenticationEntryPoint() {
        return new RestAuthenticationEntryPoint();
    };

    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Bean
    public JwtTokenUtil jwtTokenUtil(){return new JwtTokenUtil();}
}
